<template>
  <div class="k-g2ftbq">
    <LuckyDraw @start="start" @animationOver="animationOver" @winCounts="updateWinCounts" :id="prizeId" />
    <!-- 新增显示抽奖耗时 -->
    <p v-if="drawDuration">本次抽奖耗时: {{ drawDuration }} 秒</p>
    <!-- 展示每种奖品的中奖次数 -->
    <ul>
      <li v-for="(count, index) in winCounts" :key="index">
        奖品（{{ prizeList[index].name }}）的中奖次数: {{ count }}
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import LuckyDraw from '@/components/luckydraw.vue'
import { ref } from 'vue'
const prizeId = ref<number | string>('') // 奖品id,后端获取
// 新增记录抽奖开始时间
const drawStartTime = ref<number>(0)
// 新增记录抽奖耗时
const drawDuration = ref<number>(0)
// 定义一个响应式变量来保存中奖次数
const winCounts = ref<number[]>(new Array(8).fill(0));
// 定义一个方法来更新中奖次数
const updateWinCounts = (newWinCounts: number[]) => {
  winCounts.value = newWinCounts;
};

// 定义奖品列表，这里简单模拟从组件中获取的结构
const prizeList = [
  { id: 0, name: '5' },
  { id: 1, name: '50' },
  { id: 2, name: '15' },
  { id: 3, name: '20' },
  { id: 4, name: '120' },
  { id: 5, name: 'thanks' },
  { id: 6, name: '25' },
  { id: 7, name: '10' },
]

const start = async () => {
  // 重置状态
  prizeId.value = ''
  drawStartTime.value = 0
  drawDuration.value = 0

  
  // 记录抽奖开始时间
  drawStartTime.value = Date.now()
  setTimeout(() => {
 
  // 根据奖品数额计算中奖概率
  const probabilities = prizeList.map(item => {
    if (item.name === 'thanks') {
      return 0.3 // 谢谢参与设置较高概率
    }
    // 金额越大，中奖概率越小，使用金额的倒数作为概率基础
    return 1 / parseInt(item.name, 10)
  })

  // 计算总概率
  const totalProbability = probabilities.reduce((sum, prob) => sum + prob, 0)
  console.log(totalProbability, '总概率')

  // 归一化概率
  const normalizedProbabilities = probabilities.map(prob => prob / totalProbability)
  console.log(normalizedProbabilities, '归一化概率')

  // 随机选择一个中奖奖品
  const randomValue = Math.random()
  console.log(randomValue, '随机数')
  let cumulativeProbability = 0
  for (let i = 0; i < normalizedProbabilities.length; i++) {
    cumulativeProbability += normalizedProbabilities[i]
    if (randomValue < cumulativeProbability) {
      prizeId.value = prizeList[i].id
      break
    }
  }
}, 1500)
}

// 动画结束 处理对应弹窗
const animationOver = (id: number) => {
  // 记录抽奖结束时间并计算耗时
  const endTime = Date.now()
  drawDuration.value = (endTime - drawStartTime.value) / 1000
  alert(`中奖id:${id}`)
}
</script>

<style lang="less">
.k-g2ftbq {
  font-size: 16px;
  background: #2d8fff;
  min-height: 100vh;
  box-sizing: border-box;
  background-size: 100% auto;
}
</style>
